package com.seari.custody.service.Impl;

import com.alibaba.fastjson.JSONObject;
import com.seari.custody.bean.File;
import com.seari.custody.bean.Project;
import com.seari.custody.bean.TechnicalAccessory;
import com.seari.custody.bean.TechnicalOutline;
import com.seari.custody.component.MinIoUtil;
import com.seari.custody.constant.BusinessConstant;
import com.seari.custody.enums.MeetingFileType;
import com.seari.custody.mapper.ReportProjectMapper;
import com.seari.custody.pojo.RecordsSystsemResponse;
import com.seari.custody.pojo.RecordsSystsemResquest;
import com.seari.custody.service.ReportProjectService;
import com.seari.custody.util.HandlerNullUtils;
import com.seari.custody.util.HttpClientUtil;
import com.seari.custody.util.JwtTokenUtils;
import com.seari.custody.util.ThreadUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.*;

@Service("ReportProjectService")
@Slf4j
public class ReportProjectServiceImpl implements ReportProjectService {

    @Value("${record.url}")
    private String recordUrl;//档案系统下载接口地址

    @Value("${minio.projectpdf.bucket}")
    private String minioProjectPdf;//minio project pdf桶地址

    @Value("${minio.projectword.bucket}")
    private String minioProjectWord;//minio project word桶地址

    @Value("${minio.url}")
    private String minioUrl;//minio 查看pdf地址

    @Value("${minio.projectotherattach.bucket}")
    private String projectOtherAttach;

    @Autowired
    private ReportProjectMapper reportProjectMapper;

    @Autowired
    private MinIoUtil minIoUtil;

    @Autowired
    private OutlineProjectServiceImpl outlineProjectServiceImpl;


    @Override
    public int getProjectNumByNo(String no, String type) throws Exception {

        return reportProjectMapper.getProjectNumByNo(no, type);
    }


    @Override
    public void addIssueProject(Project project) throws Exception {

        reportProjectMapper.addIssueProject(project);
    }

    @Override
    public void addFileInfo(List<File> files, String account) throws Exception {
        //将文件信息入库   将文件下载到minio文件服务器
        HttpClientUtil httpClientUtil = HttpClientUtil.getInstance();
        for (File f : files) {

            String[] fileType = f.getFileName().split("\\.");

            f.setExtName(fileType[fileType.length - 1]);

            //只下载工程信息概况类型的文件
            if (f.getFiletype().contains("工程信息概况")) {
                //处理文件名称
                f.setFileName(f.getFileName().replace("." + f.getExtName(), f.getId() + "." + f.getExtName()));

                if (f.getExtName().equals("docx") || f.getExtName().equals("pdf") || f.getExtName().equals("PDF")) {

                    if (f.getExtName().equals("pdf") || f.getExtName().equals("PDF")) {
                        String pdfUrl = "/" + minioProjectPdf + "/" + f.getFileName();
                        f.setUrl(pdfUrl);
                    }

                    if (f.getExtName().equals("docx")) {
                        String wordUrl = "/" + minioProjectWord + "/" + f.getFileName();
                        f.setUrl(wordUrl);
                    }
                    ThreadUtils.fixedThreadPool.execute(new Runnable() {
                        @Override
                        public void run() {
                            downRecodeFile(f, account);
                        }
                    });
                }
            }
        }

        reportProjectMapper.addFileInfo(files);

    }

    //下载文件并上传到minio
    public synchronized void downRecodeFile(File f, String account) {

        try {
            //第一次请求获取 档案系统下载链接
            //档案系统文件ID
            String fileEmcId = f.getFileEmcId();
            RecordsSystsemResquest recordsSystsemResquest = new RecordsSystsemResquest();
            recordsSystsemResquest.setFILE_ID(fileEmcId);
            //目前使用用户工号下载  同时使用一个用户下载会造成阻塞
            String reponseCon = HttpClientUtil.sendHttpPostJsonHasHeader(recordUrl, JSONObject.toJSONString(recordsSystsemResquest), account);
            //响应
            RecordsSystsemResponse recordsSystsemResponse = JSONObject.parseObject(reponseCon, RecordsSystsemResponse.class);
            String downUrl = recordsSystsemResponse.getRESPONSE();
            //第二次请求 获取文件到本地
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGet httpget = new HttpGet(downUrl);
            CloseableHttpResponse response = client.execute(httpget);

            HttpEntity entity = response.getEntity();
            InputStream is = entity.getContent();

            String contentType = f.getExtName();

            if (f.getExtName().equals("pdf") || f.getExtName().equals("PDF")) {
                minIoUtil.putObject(minioProjectPdf, f.getFileName(), is, contentType); //把文件放置Minio桶(pdf文件夹)
            } else {
                minIoUtil.putObject(minioProjectWord, f.getFileName(), is, contentType); //把文件放置Minio桶(word文件夹)
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public List<Project> selectIssueProject(String type, String selectType, String userNumber, String noSelect, String projectNameSelect, String reviewStatus, String agenda,String status ) throws Exception {
        List<Project> projectList;
        List<String> projectId = new ArrayList();
        List<TechnicalOutline> monitoringTheOutline;
        // 条件判断-征询类
        List<Integer> category;
        List<Integer> consult;
        // 条件判断-监护大纲
        List<Integer> outlineStatus;
        // 条件判断-专项保护方案
        List<Integer> specialProject;
        // 条件判断-许可类
        List<Integer> permission;
        if (agenda.equals("0")) {
            category = Arrays.asList(1, 2, 3, 4);
            consult = Arrays.asList(1, 3, 5);
            outlineStatus = Arrays.asList(1, 3, 5, 6);
            specialProject = Arrays.asList(7);
            permission = Arrays.asList(1, 3, 4, 5);
        } else {
            category = Arrays.asList(1, 2, 3, 4);
            consult = Arrays.asList(2, 6);
            outlineStatus = Arrays.asList(2, 4, 7);
            specialProject = Arrays.asList(8, 9);
            permission = Arrays.asList(2, 6);
        }
        if (selectType.equals(BusinessConstant.SELECR_TYPE_ZX)) {//征询
            projectList = reportProjectMapper.selectIssueProjectZXList(type, userNumber, noSelect, projectNameSelect, reviewStatus, category, consult,status);
        } else if (selectType.equals(BusinessConstant.SELECR_TYPE_JHDG)) {//监护大纲
            projectList = reportProjectMapper.selectIssueProjectJHDGList(type, userNumber, noSelect, projectNameSelect, reviewStatus, outlineStatus,status);
        } else if (selectType.equals(BusinessConstant.SELECR_TYPE_ZXBHFA)) {//专项保护方案
            projectList = reportProjectMapper.selectIssueProjectZXBHFAList(type, userNumber, noSelect, projectNameSelect, reviewStatus, specialProject,status);
        } else {//许可
            projectList = reportProjectMapper.selectIssueProjectXKList(type, userNumber, noSelect, projectNameSelect, reviewStatus, permission,status);
        }

        // 获取项目日期并封装成list
        for (Project p : projectList) {
            projectId.add(p.getUuid());
        }

        if (selectType.equals(BusinessConstant.SELECR_TYPE_ZX)) {//征询
            monitoringTheOutline = reportProjectMapper.technicalAuditOpinionSelect(projectId);
        } else if (selectType.equals(BusinessConstant.SELECR_TYPE_JHDG)) {//监护大纲
            //更新日期
            monitoringTheOutline = reportProjectMapper.monitoringTheOutlineSelect(projectId);
        } else if (selectType.equals(BusinessConstant.SELECR_TYPE_ZXBHFA)) {//专项保护方案
            monitoringTheOutline = reportProjectMapper.specialProtectionProgramServer(projectId);
        } else {//许可
            monitoringTheOutline = reportProjectMapper.technicalAuditOpinionSelect(projectId);
        }

        for (Project p : projectList) {
            p.setReviewStatus(BusinessConstant.reviewStatusMap.get(p.getReviewStatus()));
            for (int i = 0; i < monitoringTheOutline.size(); i++) {
                String projectId1 = monitoringTheOutline.get(i).getProjectId();
                Date projectId2 = monitoringTheOutline.get(i).getCreateTime();
                if (projectId1.equals(p.getUuid())) {
                    p.setUpdateTime(projectId2);
                }
            }
            if (selectType.equals(BusinessConstant.SELECR_TYPE_ZX)) { //征询
                //待办状态以数字表示
                p.setPendingState(p.getFlowStatus());
                //待办状态以文字表示
                p.setFlowStatus(BusinessConstant.flowStatusMap.get(p.getFlowStatus()));
            } else if (selectType.equals(BusinessConstant.SELECR_TYPE_JHDG)) {  //监护大纲
                p.setPendingState(p.getOutlineStatus());
                p.setFlowStatus(BusinessConstant.outlineStatus.get(p.getOutlineStatus()));
            } else if (selectType.equals(BusinessConstant.SELECR_TYPE_ZXBHFA)) {//专项保护方案
                p.setPendingState(p.getFlowStatus());
                p.setFlowStatus(BusinessConstant.flowStatusMap.get(p.getFlowStatus()));
            } else {//许可
                p.setPendingState(p.getFlowStatus());
                p.setFlowStatus(BusinessConstant.flowStatusMap.get(p.getFlowStatus()));
            }
            p.setType(BusinessConstant.xkTypeMap.get(p.getType()));
        }


        return projectList;
    }


    @Override
    public Project getProgramInfoByUuid(String uuid, String selectType) throws Exception {
        Project p = reportProjectMapper.getProgramInfoByUuid(uuid);

        if (!HandlerNullUtils.objectIsNull(p)) {
            p.setReviewStatus(BusinessConstant.reviewStatusMap.get(p.getReviewStatus()));
            p.setCategory(p.getType());
            p.setType(BusinessConstant.xkTypeMap.get(p.getType()));
            if (!HandlerNullUtils.objectIsNull(p.getLineType())) {
                String[] strList = p.getLineType().split(",");
                StringBuilder s = new StringBuilder();

                for (int i = 0; i < strList.length; i++) {
                    s.append(BusinessConstant.lineTypeMap.get(strList[i]));
                    s.append(",");
                }
                p.setLineType(s.toString().substring(0, s.length() - 1));
            }

            if (!HandlerNullUtils.objectIsNull(p.getStationFlag())) {
                String[] strList = p.getStationFlag().split(",");
                StringBuilder s = new StringBuilder();

                for (int i = 0; i < strList.length; i++) {
                    s.append(BusinessConstant.stationFlagMap.get(strList[i]));
                    s.append(",");
                }
                p.setStationFlag(s.toString().substring(0, s.length() - 1));
            }

            if (!HandlerNullUtils.objectIsNull(p.getStationArea())) {
                String[] strList = p.getStationArea().split(",");
                StringBuilder s = new StringBuilder();
                for (int i = 0; i < strList.length; i++) {
                    s.append(BusinessConstant.stationAreaMap.get(strList[i]));
                    s.append(",");
                }
                p.setStationArea(s.toString().substring(0, s.length() - 1));
            }

            // 待办状态判断||退回按钮是否存在
            if (selectType.equals("1")) {
                p.setStatus(BusinessConstant.outlineStatus.get(p.getOutlineStatus()));
                //待办状态小于4时退回状态存在
                if (Integer.parseInt(p.getOutlineStatus()) < 4) {
                    p.setReturnState("1");
                } else {
                    p.setReturnState("0");
                }
            } else {
                if (Integer.parseInt(p.getFlowStatus()) < 4) {
                    p.setReturnState("1");
                } else {
                    p.setReturnState("0");
                }
                p.setStatus(BusinessConstant.flowStatusMap.get(p.getFlowStatus()));
            }


        }
        return p;
    }

    @Override
    public List<Project> getProgramHisInfoListByNo(String no) throws Exception {

        return reportProjectMapper.getProgramHisInfoListByNo(no);
    }

    @Override
    public List<File> getFileInfoByProjectUuid(String uuid) throws Exception {

        List<File> filePdf = new ArrayList<File>();
        List<File> fileWord = new ArrayList<File>();

        List<File> othersfile = new ArrayList<File>();

        List<File> fileRe = new ArrayList<File>();

        List<File> files = reportProjectMapper.getFileInfoByProjectUuid(uuid);

        for (File f : files) {

            if (f.getFiletype().contains("工程信息概况") && (f.getExtName().equals("pdf") || f.getExtName().equals("PDF") || f.getExtName().equals("docx"))) {
                //给前台标识 工程信息概况
                f.setFileTypeCode("1");
                f.setUrl(minioUrl + f.getUrl());
                if (f.getExtName().equals("pdf") || f.getExtName().equals("PDF")) {
                    filePdf.add(f);
                } else {
                    fileWord.add(f);
                }
            } else {
                f.setFileTypeCode("0");
                othersfile.add(f);
            }
        }

        if (filePdf.size() > 1) {
            Optional<File> filePdfMax = filePdf.stream().max(Comparator.comparing(File::getFileEmcId));
            fileRe.add(filePdfMax.get());
        } else {
            fileRe.addAll(filePdf);
        }

        if (fileWord.size() > 1) {
            Optional<File> fileWordMax = fileWord.stream().max(Comparator.comparing(File::getFileEmcId));
            fileRe.add(fileWordMax.get());
        } else {
            fileRe.addAll(fileWord);
        }

        fileRe.addAll(othersfile);
        return fileRe;
    }

    @Override
    public void deleteProjectotherattachFileByUuid(String aessId) throws Exception {

        TechnicalAccessory technicalAccessory = reportProjectMapper.selectProjectotherattachInfoByUuid(aessId);
        reportProjectMapper.deleteProjectotherattachFileByUuid(aessId);
        // minio 删除文件
        minIoUtil.removeObject(projectOtherAttach, technicalAccessory.getAessName());
    }

    @Override
    public List<Project> projectSelect(Map<String, String> map) throws Exception {
        return reportProjectMapper.projectSelect(map);
    }

    @Override
    public void updateProjectVersionStatus(Map<String, String> map) throws Exception {
        reportProjectMapper.updateProjectVersionStatus(map);
    }

    @Override
    public Map<String, Object> saverFileNumber(String projectUuid) throws Exception {
        return reportProjectMapper.saverFileNumber(projectUuid);
    }

    @Override
    public List<Map<String, Object>> engineeringInformationSummary(Map<String, Object> map) throws Exception {

        String uuid = map.get("uuid").toString();
        List<Map<String, Object>> stringObjectMap = reportProjectMapper.savaerSort(uuid);

        for (int i = 0; i < stringObjectMap.size(); i++) {
            String file_type = stringObjectMap.get(i).get("file_type").toString();
            String ext_name = stringObjectMap.get(i).get("ext_name").toString();
            Object url = stringObjectMap.get(i).get("url");
            List<Map<String, Object>> maps = reportProjectMapper.particularsSort(file_type, uuid);
            List list1 = new ArrayList();
            List list2 = new ArrayList();
            List list3 = new ArrayList();
            for (int j = 0; j < maps.size(); j++) {
                String emc_id = maps.get(j).get("file_emc_id").toString();
                if (maps.get(j).get("url") != null && !maps.get(j).get("url").equals("")) {
                    String url1 = maps.get(j).get("url").toString();
                    String url2 = "http://172.20.41.71:9000" + url1;
                    list2.add(url2);
                }
                list1.add(emc_id);
                list3.add(j + 1);
            }
            // 添加档案编号list1
            stringObjectMap.get(i).put("emc_id", list1);
            stringObjectMap.get(i).put("urlString", list2);
            // 是否可查看
            Boolean ext1 = ext_name.equals("pdf");
            Boolean ext2 = file_type.contains("工程信息概况");
            stringObjectMap.get(i).put("examine", ext1 == true & ext2 == true ? "1" : "0");
            stringObjectMap.get(i).put("exists", (url != null && !url.equals("")) ? "1" : "0");
            stringObjectMap.get(i).put("versions", list3);
            //拼接URL地址
        }


//        String url="http://172.20.41.71:9000";
//        List<Map<String, Object>> maps = reportProjectMapper.saverEngineering(url, uuid);
//        for(int i=0;i<maps.size();i++){
//            String ext_name = maps.get(i).get("ext_name").toString();
//            String file_type = maps.get(i).get("file_type").toString();
//            if(ext_name.equals("pdf")&&file_type.contains("工程信息概况")){
//                maps.get(i).put("examine","1");
//            }else{
//                maps.get(i).put("examine","0");
//            }
//        }
        return stringObjectMap;
    }

    @Override
    public String replacepdf(Map<String, String> map) {
        String selectType = map.get("selectType");
        String uuid = map.get("uuid");
        String token = map.get("token");
        // 生成用户名
        String userNumber = JwtTokenUtils.getUserNumber(token.substring(JwtTokenUtils.TOKEN_PREFIX.length()));
        String replaceString = "";
        switch (selectType) {
            //监护大纲
            case "1":
                replaceString = outlineProjectServiceImpl.getOutlineProjectFile(uuid, userNumber, MeetingFileType.OUTLINE_PROJECT_PDF);
                break;
            //征询类
            case "2":
                String consult = reportProjectMapper.technicalReviewPdf(uuid);
                replaceString = "http://172.20.41.71:9000" + consult;
                break;
            //许可类
            case "3":
                String permission = reportProjectMapper.technicalReviewPdf(uuid);
                replaceString = "http://172.20.41.71:9000" + permission;
                break;
            //专项保护方案
            case "4":
                String specialProgram = reportProjectMapper.protectionProgramPdf(uuid);
                replaceString = "http://172.20.41.71:9000/projectpdf/" + specialProgram;
                break;
        }

        return replaceString;
    }

    @Override
    public List<Map<String, Object>> pullDownServer(Map<String, String> map) {
        String selectType = map.get("selectType");
        Map<String, Object> map1 = new HashMap<>();

        List<Map<String, Object>> map2 = new ArrayList<>();
        List<String> ArraysasList = Arrays.asList("待处理", "资料校对", "处理中", "已发送", "技术要求表被退回待处理", "技术要求表被修改待确认", "已完结");
        List<String> ArraysasList1 = Arrays.asList("待处理", "资料校对", "处理中", "专项草稿审核", "技审草稿被退回待处理", "已完结");
        List<String> ArraysasList2 = Arrays.asList("处理中", "已退回", "已完结");
        //技审意见审核状态：1.待处理 2.资料校对 3.处理中  4.专项草稿审核 5.技审草稿被退回待处理 6.已完结 7.处理中：专项保护方案 8.已退回：专项保护方案  9.已完结：专项保护方案已完结
        switch (selectType) {
            case "1":
                for (int i = 0; i < ArraysasList.size(); i++) {
                    Map<String, Object> map3 = new HashMap<>();
                    String name = ArraysasList.get(i);
                    Integer value = i;
                    map3.put("name", name);
                    map3.put("value", value+1);
                    map2.add(map3);
                }
                break;
            case "2":

                for (int i = 0; i < ArraysasList1.size(); i++) {
                    Map<String, Object> map3 = new HashMap<>();
                    String name = ArraysasList1.get(i);
                    Integer value = i;
                    map3.put("name", name);
                    map3.put("value", value+1);
                    map2.add(map3);
                }
                break;
            case "3":
                for (int i = 0; i < ArraysasList1.size(); i++) {
                    Map<String, Object> map3 = new HashMap<>();
                    String name = ArraysasList1.get(i);
                    Integer value = i;
                    map3.put("name", name);
                    map3.put("value", value+1);
                    map2.add(map3);
                }
                break;
            case "4":
                for (int i = 0; i < ArraysasList2.size(); i++) {
                    Map<String, Object> map3 = new HashMap<>();
                    String name = ArraysasList2.get(i);
                    Integer value = i + 7;
                    map3.put("name", name);
                    map3.put("value", value);
                    map2.add(map3);
                }
                break;

        }


        return map2;
    }


}
